package com.gerald.shop.controller;

import com.gerald.shop.common.utils.R;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author Gerald 2022/1/7 21:03
 * description:
 */
@RequestMapping("/system/file")
@RestController
@Slf4j
public class FileController {

    @Autowired
    private FastFileStorageClient fastClient;
    /**
     * @author Gerald 2022/1/8 17:16
     * description:拼接地址域名
     * 配置文件中的home http://192.168.47.128:8080/
     */
    @Value("${fdfs.home}")
    private String home;

    @PostMapping("/imageUpload")
    public R imageUpload(MultipartFile file){
//        log.debug("fileName:{}", file.getOriginalFilename());
//        log.debug("fileType:{}", file.getContentType());
//        log.debug("fileSize:{}", file.getSize());

        //根据文件名获取文件后缀
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        //文件地址
        StorePath storePath = null;
        try {
//            log.debug("fileIp:{}", file.getInputStream());
            storePath = fastClient.uploadFile(file.getInputStream(), file.getSize(), extension, null);
            String filePath = home + storePath.getFullPath();
            return R.ok().put("path", filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.ok();
    }
}
